package com.central.apps.handler.purchase;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.common.constant.AppConstant;
import com.central.app.service.HandlerService;
import com.central.apps.dao.MaterialInventory.goWarehouseDao;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.exception.service.ServiceException;
import com.central.common.web.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 处理询价单业务逻辑
 *
 * @author lidachao
 * @date 2022/9/5
 */
@Component
@Slf4j
public class InquirySheetHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Override
    public String validateSave(String app, String objName, Map<String, Object> data) throws Exception {
        if (objName.equals("gq_issupplier")) {
            String isnum = MapUtils.getString(data,"isnum");

            if (StringUtils.isEmpty(isnum)) {
                return "请先保存询价单数据之后再选择供应商";
            }
        }
        return null;
    }

    @Override
    public void beforDelete(String app, String objName, Long id, boolean isLogic) {
        if ("inquirysheet1App".equals(app)){
            if ("gq_inquirysheet".equals(objName)){
                // 更新采购计划汇总行标记
                handlerService.updateBySql("update gq_ppsummaryline set converttorfq = 0 where id in (select ppslid from gq_inquirysheetline where isid = " + id + ")");
                List<Map<String, Object>> bySql = handlerService.findBySql("select ppid from gq_inquirysheet where id=" + id +"");
                if (CollectionUtils.isNotEmpty(bySql)){
                    Map<String, Object> map = bySql.get(0);
                    String ppid = MapUtils.getString(map, "ppid");
                    String rfqnot="未询价";
                    handlerService.updateBySql("update gq_purchaseplan set rfqnot='"+rfqnot+"' where  id = '" + ppid+"'");
                }

            }
        }else if ("inquirysheetApp".equals(app)){
            if ("gq_inquirysheet".equals(objName)){
                // 更新采购计划汇总行标记
                handlerService.updateBySql("update gq_ppsummaryline set converttorfq1 = 0 where id in (select ppslid from gq_inquirysheetline where isid = " + id + ")");
            }
        }

    }

    //询价单需求变更
//    @Override
//    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
//        if("submit".equals(flowNode.getId())) {
//            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_issupplier where isid = " + id);
//
//            if (CollectionUtils.isEmpty(list)) {
//                return "请选择供应商并添加相应的报价信息！";
//            }
//
//            list = handlerService.findBySql("select id from gq_isoffer where isid = " + id);
//
//            if (CollectionUtils.isEmpty(list)) {
//                return "请添加供应商相应的报价信息！";
//            }
//        }
//
//        return null;
//    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if (objName.equals("gq_isoffer") && !isUpdate) {
            //这块需求飞哥变了，之前报价列表上面为选择供应商信息，现在改为询价物料
            //新需求是：同一供应商相同数量只允许报一次价
                     //同一供应商根据数量不同多次报价
            //2023/1/28飞哥需求变了，供应商可以无限制报价，不用根据数量限制
//            String inquiryitemid = MapUtils.getString(data, "inquiryitemid");//询价物料id
//            String itemnum = MapUtils.getString(data, "itemnum");//物料编码
//            String quantity = MapUtils.getString(data, "quantity");//数量
//            String suppliernum = MapUtils.getString(data, "suppliernum");//供应商编号
//            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_isoffer where inquiryitemid = '" + inquiryitemid + "' and itemnum = '"
//                    + itemnum + "' and quantity = '" + quantity + "' and suppliernum = '" + suppliernum + "'");
//            if(CollectionUtils.isNotEmpty(bySql)){
//                throw new ServiceException("同一供应商对同一询价物料的相同数量只允许报一次价");
//            }

//            String isnum = MapUtils.getString(data,"isnum");
//            String itemnum = MapUtils.getString(data,"itemnum");
//            String suppliernum = MapUtils.getString(data,"suppliernum");
//
//            List<Map<String, Object>> list = handlerService.findBySql("select itemnum from gq_isoffer where isnum = '" + isnum
//                    + "' and itemnum = '" +itemnum+ "' and suppliernum = '" + suppliernum + "'");
//
//            if (CollectionUtils.isNotEmpty(list)) {
//                throw new ServiceException("供应商已经存在相同物料的报价信息！");
//            }
//        } else if (objName.equals("gq_isoffer") && isUpdate) {
//            String isnum = MapUtils.getString(data,"isnum");
//            String suppliernum = MapUtils.getString(data,"suppliernum");
//            String itemnum = MapUtils.getString(data,"itemnum");
//            String isawared = MapUtils.getString(data,"isawared");
//
//            if ("1".equals(isawared)) {
//                List<Map<String, Object>> list = handlerService.findBySql("select itemnum from gq_isoffer where isnum = '" + isnum
//                        + "' and itemnum = '" +itemnum+ "' and isawared = '" + isawared + "' and suppliernum != '" + suppliernum + "'");
//
//                if (CollectionUtils.isNotEmpty(list)) {
//                    throw new ServiceException("该物资已采纳其他供应商，请取消该物资其它供应商的采纳后再选择！");
//                }
//            }
        } else if (objName.equals("gq_inquirysheetline")) {
            Integer ppid = MapUtils.getInteger(data,"ppid");
            String itemnum = MapUtils.getString(data,"itemnum");

            handlerService.findBySql("update gq_ppsummaryline set converttorfq = 1 where ppid = " + ppid
                        + " and itemnum = '" +itemnum+ "'");
        } else if (objName.equals("gq_inquirysheet") && isUpdate) {
            String isid = MapUtils.getString(data, "id");
            String isnum = MapUtils.getString(data, "isnum");
            String ppid = MapUtils.getString(data, "ppid");
            String type = MapUtils.getString(data, "type");
            String ppnum = MapUtils.getString(data, "ppnum");
            List<Map<String, Object>> isList = handlerService.findBySql("SELECT ppnum from gq_inquirysheet where id = " + isid);

            if (CollectionUtils.isEmpty(isList)) {
                //插入采购计划行到询价单行信息
                addIsLine(isid, isnum, ppid,type);
            } else {
                Map<String, Object> isMap = isList.get(0);
                String oldPpNum = MapUtils.getString(isMap, "ppnum");

                if (!ppnum.equals(oldPpNum)) {
                    // 删除询价单行
                    handlerService.updateBySql("delete from gq_inquirysheetline where isid = " + isid);
                    // 更新采购计划行标记
                    handlerService.updateBySql("update gq_ppsummaryline set converttorfq = 0 where id in (select ppslid from gq_inquirysheetline where isid = " + isid + ")");

                    //插入采购计划行到询价单行信息
                    addIsLine(isid, isnum, ppid,type);
                } else {
                    List<Map<String, Object>> islList = handlerService.findBySql("SELECT id from gq_inquirysheetline where isid = " + isid);

                    if (CollectionUtils.isEmpty(islList)) {
                        //插入采购计划行到询价单行信息
                        addIsLine(isid, isnum, ppid,type);
                    }
                }
            }
        }
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if (objName.equals("gq_inquirysheet") && !isUpdate){
            String isid = MapUtils.getString(data, "id");
            String isnum = MapUtils.getString(data, "isnum");
            String ppid = MapUtils.getString(data, "ppid");
            String type = MapUtils.getString(data, "type");//1为询价单2为报价单
            //插入采购计划行到询价单行信息
            addIsLine(isid, isnum, ppid,type);
        }
    }

    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        if ("inquirysheetApp".equals(app)){
            if ("getquotarmation".equals(type)){
                String isnum = MapUtils.getString(params, "isnum");
                List<Map<String, Object>> bySql = handlerService.findBySql("SELECT suppliernum from gq_issupplier where isnum ='" + isnum + "'");
                if (CollectionUtils.isNotEmpty(bySql)) {
                    int page = 1;
                    int limit = 10;
                    if (MapUtils.getInteger(params, AppConstant.BIZ_QUERY_PAGE) != null && MapUtils.getInteger(params, AppConstant.BIZ_QUERY_LIMIT) != null) {
                        page = MapUtil.getInt(params, AppConstant.BIZ_QUERY_PAGE);
                        limit = MapUtil.getInt(params, AppConstant.BIZ_QUERY_LIMIT);
                    }

                    List<Map<String, Object>> collect = bySql.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
                    return PageResult.<Map<String, Object>>builder().data(collect).code(0).count((long) bySql.size()).build();
                }
            }
        }
        return super.operate(app, type, params);
    }

    /**
     * 插入采购计划行到询价单行信息
     *
     * @param ppid
     */
    private void addIsLine(String isid, String isnum, String ppid,String type) throws Exception {
        List<Map<String, Object>> islineDatas = new ArrayList<>();
        // 查询采购计划信息
        List<Map<String, Object>> ppList = handlerService.findBySql("select * from gq_purchaseplan where id = " + ppid);
        Map<String, Object> ppMap=null;
        if(CollectionUtils.isNotEmpty(ppList)){
            ppMap = ppList.get(0);
        }

        List<Map<String, Object>> ppslList = new ArrayList<>();
        if("1".equals(type)){//询价单
            // 查询采购计划汇总行信息
            ppslList = handlerService.findBySql("select * from gq_ppsummaryline where converttorfq = 0 and ppid = " + ppid);
        }else if ("2".equals(type)){//报价单
            ppslList = handlerService.findBySql("select * from gq_ppsummaryline where converttorfq1 = 0 and ppid = " + ppid);
        }


        // 查询采购计划汇总行信息
//        List<Map<String, Object>> ppslList = handlerService.findBySql("select * from gq_ppsummaryline where converttorfq = 0 and ppid = " + ppid);

        for (Map<String, Object> ppslMap : ppslList) {
            Integer ppslid = (Integer) ppslMap.get("id");
            // 组织询价单明细数据
            Map<String, Object> islineMap = new HashMap<>();
            islineMap.put("ppid", ppslMap.get("ppid"));
            islineMap.put("ppslid", ppslid);
            islineMap.put("isid", isid);
            islineMap.put("isnum", isnum);
            islineMap.put("itemnum", ppslMap.get("itemnum"));
            islineMap.put("itemdesc", ppslMap.get("itemdesc"));
            islineMap.put("model", ppslMap.get("model"));
            islineMap.put("specifications",ppslMap.get("specifications"));
            islineMap.put("orderqty", ppslMap.get("orderqty"));
            islineMap.put("orderunit", ppslMap.get("orderunit"));
            islineMap.put("unitcost", ppslMap.get("unitcost"));
            islineMap.put("linecost", ppslMap.get("totalcost"));
            islineMap.put("maintechtors",ppslMap.get("maintechtors"));
            islineDatas.add(islineMap);

            // 更新采购计划行标记信息
            if("1".equals(type)){//询价单
                handlerService.updateBySql("update gq_ppsummaryline set converttorfq = 1 where id = " + ppslid);
            }else if("2".equals(type)){//报价单
                handlerService.updateBySql("update gq_ppsummaryline set converttorfq1 = 1 where id = " + ppslid);
            }
        }

        // 批量插入询价单明细
        handlerService.batchInsert("inquirysheetApp","gq_inquirysheetline", islineDatas);
    }
}
